/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-4-23 下午1:30 Created by dwzhang
 */
package com.jade.framework.base.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 拼音的工具类。
 *
 * @author dwzhang
 * @version 1.0 13-4-23 下午1:30
 */
public class PinyinUtils
{
    /**
     * 获取汉字串拼音首字母，英文字符不变。
     *
     * @param chinese 汉字串
     * @return 汉语拼音首字母
     */
    public static String getFirstSpell(String chinese)
    {
        StringBuilder sb = new StringBuilder();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char anArr : arr) {
            if (anArr > 128) {
                try {
                    String[] _t = PinyinHelper.toHanyuPinyinStringArray(anArr, defaultFormat);
                    if (_t != null) {
                        sb.append(_t[0].charAt(0));
                    }
                }
                catch (BadHanyuPinyinOutputFormatCombination e) {
                    return null;
                }
            }
            else {
                sb.append(anArr);
            }
        }
        return sb.toString().replaceAll("\\W", "").trim();
    }

    /**
     * 获取汉字串拼音，英文字符不变
     *
     * @param chinese 汉字串
     * @return 汉语拼音
     */
    public static String getFullSpell(String chinese)
    {
        StringBuilder sb = new StringBuilder();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char anArr : arr) {
            if (anArr > 128) {
                try {
                    sb.append(PinyinHelper.toHanyuPinyinStringArray(anArr, defaultFormat)[0]);
                }
                catch (BadHanyuPinyinOutputFormatCombination e) {
                    return null;
                }
            }
            else {
                sb.append(anArr);
            }
        }
        return sb.toString();
    }
}
